<?php


namespace App\Http\Controller;


use App\Model\Entity\Device;

use App\Model\Entity\SensorData;
use App\Model\Entity\SensorType;
use ReflectionException;
use Swoft\Bean\Exception\ContainerException;
use Swoft\Db\Exception\DbException;
use Swoft\Exception\SwoftException;
use Swoft\Http\Message\Response;
use Swoft\Http\Server\Annotation\Mapping\Controller;
use Swoft\Http\Server\Annotation\Mapping\Middleware;
use Swoft\Http\Server\Annotation\Mapping\RequestMapping;
use Swoft\Log\Helper\Log;
use Swoole\Exception;
use App\Http\Middleware\AuthMiddleware;
/**
 * Class DataController
 * @Controller("/v1/Data")
 * @Middleware(AuthMiddleware::class)
 * @package App\Http\Controller
 */
class DataController
{
    /**
     * 查询数据
     * @RequestMapping("/v1/Data[/{deviceId}]")
     * @param $deviceId string
     * @return Response
     * @throws SwoftException
     */
    public function Get(string $deviceId): Response
    {
        $request = Context()->getRequest();
        $response = Context()->getResponse();

        $mentod = $request->getMethod();

        $headers = $request->getHeaders();


        if ($mentod == "GET")
            $data = $request->get();
        else {
            Log::error("Error!");
            return $response->withStatus(404);

        }
        if($deviceId ==null ||  $deviceId== "")
            return $response->withStatus(400)->withData(["error"=>"1","errorMsg"=>"deviceId错误"]);

        if(Context()->get("user") == null)
            return $response->withStatus(500)->withData(["errorMsg"=>"服务去错误"]);

        $pageSize = (string)50;
        $pageNo = null;
        if(isset($data["pageNo"]) && is_numeric($data["pageNo"]) && $data["pageNo"] >0 )
        {
            $pageNo = $data["pageNo"];
            if(isset($data["pageSize"]) && is_numeric($data["pageSize"]) && $data["pageSize"]>0)
                $pageSize = $data["pageSize"];

        }
        try{
            $devices = ["user"=>Context()->get("user"),"deviceId"=>$deviceId];
            if($pageNo != null) {
                $devices["pageNo"] = (string)$pageNo;
                $devices["pageSize"] = (string)$pageSize;
            }
            if(Device::join("user",'device.userid', '=', 'user.userid')->where("user.UserName",Context()->get("user"))
                    ->where("deviceId",$deviceId)->count() <= 0 )
            {
                return $response->withStatus(400)->withData(["error"=>"3","errorMsg"=>"你没有这个设备"]);
            }
            $type_name = null;
            if(isset($data["type_name"]) && !($data["type_name"] == null || $data["type_name"] == "" )) {
                if ( SensorType::where("type_name", $data["type_name"])->count() <= 0) {
                    return $response->withStatus(400)->withData(["error" => "4", "errorMsg" => "没有这个传感器标识符"]);
                }
                $type_name = $data["type_name"];
            }



            $dbRec = null;
            if($type_name == null)
            {
                $dbRec =  SensorData::join('device', 'device.deviceId', '=', 'sensor_data.deviceId')
                    ->join("user",'device.userid', '=', 'user.userid')
                    ->join("sensor_type",'sensor_type.type_name', '=', 'sensor_data.type_name')
                    ->select('sensor_data.data','sensor_data.date','sensor_type.describe','sensor_type.unit')
                    ->where("user.UserName",Context()->get("user"))->where("sensor_data.deviceId",$deviceId)->orderBy("sensor_data.date","desc");
            }
            else
            {
                $dbRec =  SensorData::join('device', 'device.deviceId', '=', 'sensor_data.deviceId')
                    ->join("user",'device.userid', '=', 'user.userid')
                    ->join("sensor_type",'sensor_type.type_name', '=', 'sensor_data.type_name')
                    ->select('sensor_data.data','sensor_data.date','sensor_type.describe','sensor_type.unit')
                    ->where("user.UserName",Context()->get("user"))->where("sensor_data.deviceId",$deviceId)
                    ->where("sensor_type.type_name",$type_name)->orderBy("sensor_data.date","desc");
            }


            if($pageNo != null)
            {
                $devices["pageAmount"] = ((int) ($dbRec->count()/$pageSize)  );
                if($dbRec->count()%$pageSize != 0)
                    $devices["pageAmount"] += 1;
                $devices["pageAmount"] = (string)$devices["pageAmount"];
                $devices["Data"] = $dbRec->forPage($pageNo,$pageSize)->get();
            }
            else
                $devices["Data"] = $dbRec->get();

            $devices["count"] = count($devices["Data"]);
            return $response->withData($devices);

        } catch (ReflectionException $e) {
            return $response->withStatus(400)->withData(["error"=>"5","errorMsg"=>$e->getMessage()]);
        } catch (ContainerException $e) {
            return $response->withStatus(400)->withData(["error"=>"5","errorMsg"=>$e->getMessage()]);
        } catch (DbException $e) {
            return $response->withStatus(400)->withData(["error"=>"5","errorMsg"=>$e->getMessage()]);
        }
    }

}
